package com.zwp.base.ext

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow

enum class Notification {
    INSTANCE
}

fun View.clickFlow() = callbackFlow {
    val listener = View.OnClickListener { trySend(Notification.INSTANCE) }
    setOnClickListener(listener)

    awaitClose {
        removeCallbacks { listener }
    }
}

fun View.longClickFlow() = callbackFlow {
    val listener = View.OnLongClickListener {
        trySend(Notification.INSTANCE)
        false
    }
    setOnLongClickListener(listener)

    awaitClose {
        removeCallbacks { listener }
    }
}

fun EditText.textChangeFlow() = callbackFlow {
    val watch = object :TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit

        override fun afterTextChanged(p0: Editable?) = Unit

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            p0?.let { trySend(it) }
        }
    }
    addTextChangedListener(watch)
    awaitClose { removeTextChangedListener(watch) }
}

